public class Solution {
    public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }

        int left = 1, right = x;


        while (left <= right) {
            int mid = left + (right - left) / 2;
            long midSquared = (long) mid * mid;

            if (midSquared == x) {
                return mid;
            } else if (midSquared < x) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }


        return right;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();


        System.out.println(solution.mySqrt(4));
        System.out.println(solution.mySqrt(8));
    }
}
